/**
 * 获取文档元信息
 */
//
// 标记各值是否取得
// 0b0001 文号
// 0b0010 标题
// 0b0100 主送
// 0b1000 发文日期

// HAS_CODE = 0b0001;
// HAS_TITLE = 0b0010;
// HAS_SEND_TO = 0b0100;
// HAS_SEND_DATE = 0b1000;
const Status = {
  HAS_CODE: 0b0001,
  HAS_TITLE: 0b0010,
  HAS_SEND_TO: 0b0100,
  HAS_SEND_DATE: 0b1000
};

const DocMeta = {
  trim(val) {
    return val.replace(/\s*/g, '');
  },

  copyToClipboard(content) {
    const inputElement = document.createElement('input');
    inputElement.value = content;
    document.body.appendChild(inputElement);
    inputElement.focus();
    inputElement.select();

    try {
      const successful = document.execCommand('copy');
      const msg = successful ? 'successful' : 'unsuccessful';
      console.log('Copying text command was ' + msg);
      alert('成功复制文档对象到剪贴板');
    } catch (err) {
      console.log('Oops, unable to copy');
    }
  },

  searchRegex(val, re) {
    const mat = val.replace(/\s*/g, '').match(re);
    return mat ? mat[0] : null;
  },

  searchCode(val) {
    const re = /^\S+〔\d{4}〕\d+号/;
    return DocMeta.searchRegex(val, re);
  },

  searchSendTo(val) {
    const re = /^\S+[：:]$/;
    return DocMeta.searchRegex(val, re);
  },

  searchSendDate(val) {
    const re = /^\d{4}年\d{1,2}月\d{1,2}日$/;
    return DocMeta.searchRegex(val, re);
  },

  getLines() {
    const doc = wps.WpsApplication().ActiveDocument;
    const paragraphs = doc.Paragraphs;
    const lines = [];
    for (let index = 1; index <= paragraphs.Count; index++) {
      const p = paragraphs.Item(index).Range.Text.trim();
      /**
       * 所有行均保留，空行不能删除，有时候需要以空行来判断内容开始结束
       */
      lines.push(p);
    }
    return lines;
  },

  prefixInteger(num, length) {
    const withPrefix = `0000000000000000${num}`;
    return withPrefix.substring(withPrefix.length - length);
  },

  parseDoc() {
    const meta = {};
    const lines = DocMeta.getLines();
    let flag = 0b0000;
    let codeLineNum = 0;

    for (const line of lines) {
      console.log('lines', line);
      // 如果没有文号，没有标题，搜索文号
      if ((flag & Status.HAS_CODE) === 0 && (flag & Status.HAS_TITLE) === 0) {
        const code = DocMeta.searchCode(line);
        if (code) {
          meta.code = code;
          codeLineNum = lines.indexOf(line);
          flag |= Status.HAS_CODE;
          continue;
        }
      }

      // 如果没有主送，搜索主送，并获得标题
      if ((flag & Status.HAS_SEND_TO) === 0) {
        const sendTo = DocMeta.searchSendTo(line);
        if (sendTo) {
          meta.send_to = sendTo;
          flag |= Status.HAS_SEND_TO;
          const sendToLineNum = lines.indexOf(line);
          /**
           * 从文号到主送之间的内容为标题，如果没有文号，就是从零行开始
           */
          const titleArray = lines.slice(codeLineNum + 1, sendToLineNum);
          // 要去除空白字符，包括垂直制表符（也就是word里面的软回车）
          meta.title = titleArray.join('').replace(/\s*/g, '');
          flag |= Status.HAS_TITLE;
          continue;
        }
      }

      // 如果没有日期，搜索日期，并获得发文单位
      if ((flag & Status.HAS_SEND_DATE) === 0) {
        const sendDate = DocMeta.searchSendDate(line);

        if (sendDate) {
          const sendDateLineNum = lines.indexOf(line);
          let backLine = sendDateLineNum;
          const sendByRows = [];
          do {
            const row = DocMeta.trim(lines[backLine - 1]);
            console.log('row', row);
            sendByRows.push(row);
            backLine -= 1;
          } while (lines[backLine - 1]);
          meta.send_by = sendByRows.filter((v) => v !== '').reverse();
          meta.send_date = sendDate;
          flag |= Status.HAS_SEND_DATE;
          continue;
        }
      }

      if (
        flag ===
        (Status.HAS_CODE |
          Status.HAS_TITLE |
          Status.HAS_SEND_TO |
          Status.HAS_SEND_DATE)
      ) {
        break;
      }
    }

    return meta;
  },

  lineStringify(obj) {
    return `${obj.send_date}\t${obj.code}\t${obj.title}`;
  },

  getMetaData(type = 'object') {
    const meta = DocMeta.parseDoc();
    const result =
      type === 'object' ? JSON.stringify(meta) : DocMeta.lineStringify(meta);
    DocMeta.copyToClipboard(result);
  }
};
